/**
 * @Module   : Wechat oauth Module
 * @Brief   : Process Wechat oauth
 */
let express = require('express');
let router = express.Router();
let request = require('request');
let config = require('../config/config')
let AV = require('leancloud-storage');
let superagent = require('superagent');
let constant = require('../config/constant')
const fs = require('fs');
const sha1 = require('sha1')
let Redis = require('ioredis');
let redis = new Redis(6379);     // 192.168.1.1:6379
router.post('/get_time', function (req, res, next) {
    let time = new Date()
    res.send({
        code: 100,
        time: time
    })
});

router.post('/get_count',async function (req, res, next) {
    let joinNum = await redis.get(constant.JOIN_NUM);
    let pollNum = await  redis.get(constant.POLL_NUM);
    let userNum = await  redis.get(constant.USER_NUM);
    if(joinNum && pollNum && userNum){
        res.send({
            code: 100, data: {
                join: joinNum,
                poll:pollNum,
                user:userNum,
            }
        });
        return;
    }

    let joincount = new AV.Query('Join');
    let joinResult = await joincount.count();
    redis.set(constant.JOIN_NUM, joinResult, "ex", 5);
    let pollcount = new AV.Query('Poll');
    let pollResult =await pollcount.count();
    redis.set(constant.POLL_NUM, pollResult, "ex", 5);
    let usercount = new AV.Query('UserInfo');
    let userResult = await usercount.count();
    redis.set(constant.USER_NUM, userResult, "ex", 5);
    console.log(joinResult, pollResult, userResult);
    res.send({
        code: 100, data: {
            join: joinResult,
            poll:pollResult,
            user:userResult,
        }
    });
});

router.post('/get_signsdk', async function (req, res, next) {
    let ticket = await redis.get('ticket');
    if (ticket) {
        console.log("ticket 存在 : " + ticket);
        let timestamp = Date.now().toString().slice(-10)
        let noncestr = 'WlddIECldl48D3'
        let url = req.body.url
        //  数据存储对象
        let data = {
            jsapi_ticket: ticket,
            timestamp: timestamp,
            noncestr: noncestr,
            url: url
        }
        // 键数组排序
        let baseArr = ['jsapi_ticket', 'timestamp', 'noncestr', 'url'].sort()

        let str = ''

        for (let i = 0; i < 4; i++) {
            str += baseArr[i] + '=' + data[baseArr[i]] + '&'
        }
        str = str.slice(0, -1)

        let signature = sha1(str)
        res.send({
            code: 100, data: {
                sdk_appId: config.APPID,
                timestamp: timestamp,
                nonceStr: noncestr,
                signature: signature
            }
        })
        return;
    }

    let tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.APPID + '&secret=' + config.SECRET;
    let result = await superagent.get(tokenUrl);
    console.log(result.body);
    if (result.body && result.body.access_token) {
        let ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + result.body.access_token + '&type=jsapi';
        let ticketResult = await superagent.get(ticketUrl);
        console.log(ticketResult.body);
        if (ticketResult.body.errcode === 0) {
            let ticket = ticketResult.body.ticket;
            redis.set(constant.TICKET, ticket, "ex", 6000);
            console.log("更新ticket");
            let timestamp = Date.now().toString().slice(-10);
            let noncestr = 'WlddIECldl48D3';
            let url = req.body.url;
            //  数据存储对象
            let data = {
                jsapi_ticket: ticket,
                timestamp: timestamp,
                noncestr: noncestr,
                url: url
            };
            // 键数组排序
            let baseArr = ['jsapi_ticket', 'timestamp', 'noncestr', 'url'].sort();

            let str = '';

            for (let i = 0; i < 4; i++) {
                str += baseArr[i] + '=' + data[baseArr[i]] + '&'
            }
            str = str.slice(0, -1);

            let signature = sha1(str);

            res.send({
                code: 100, data: {
                    sdk_appId: config.APPID,
                    timestamp: timestamp,
                    nonceStr: noncestr,
                    signature: signature
                }
            })
        }
        else{
            res.json({
                code: -1,
                msg: '获取ticket'
            })
        }
    }
    else {
        res.json({
            code: -1,
            msg: '获取access_token失败'
        })
    }
});


module.exports = router;